package com.sali.回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 排列
 */
public class LeetCode_47 {

    public static void main(String[] args) {
//        int[] nums = new int[]{1, 1, 2};
        int[] nums = new int[]{1, 2, 3};
        List<List<Integer>> lists = permuteUnique(nums);
        for (List<Integer> list : lists) {
            for (Integer en : list) {
                System.out.print(en + " ");
            }
            System.out.println();
        }
    }

    static List<List<Integer>> res = new ArrayList<>();
    static List<Integer> path = new ArrayList<>();

    public static List<List<Integer>> permuteUnique(int[] nums) {
        if (nums == null || nums.length == 0) {
            return res;
        }
        Arrays.sort(nums);
        boolean[] visited = new boolean[nums.length];
        getRes(nums, visited);
        return res;
    }

    private static void getRes(int[] nums, boolean[] visited) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int index = 0; index < nums.length; index++) {
            if (visited[index] || (index > 0 && (nums[index] == nums[index - 1]) && (visited[index - 1] == false))) {
                continue;
            }
            visited[index] = true;
            path.add(nums[index]);
            getRes(nums, visited);
            path.remove(path.size() - 1);
            visited[index] = false;
        }


    }

}
